package com.sas.web.articles;

import java.util.HashSet;
import java.util.Set;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;


import com.sas.domain.Article;
import com.sas.domain.ArticleField;
import com.sas.model.EntityModel;
import com.sas.repository.ArticleFieldRepository;
import com.sas.repository.ArticleRepository;
import com.sas.web.SasBasePage;
import com.sas.web.panel.articles.ArticleInfoPanel;

public class ArticleAddPage extends SasBasePage {
	@SpringBean
	private ArticleRepository articleRepository;
	
	@SpringBean
	private ArticleFieldRepository articleFieldRepository;
	
	private transient String code;
	private transient String name;
	private transient String description;
	private transient Double weight = 0.0;
	private transient Double netWeight = 0.0;
	private transient Double height = 0.0;
	private transient Double width = 0.0;
	private transient Double priceSell = 0.0;
	
	private static final String ALL = "todos";
	
	@SuppressWarnings("serial")
	public ArticleAddPage () {
		Form<Article> form = new Form<Article>("form", new CompoundPropertyModel<Article>(this));
		form.add(new ArticleInfoPanel("articleInfo"));
		form.add(new Button("save", new ResourceModel("save")) {
			@Override
			public void onSubmit() {
				Article art = new Article(code, name, description, weight, netWeight, height, width, priceSell);
				if (articleRepository.exists(art)) {
					error(getString("Article already exists"));
					return;
				}
				
				ArticleField all = articleFieldRepository.findByName(ALL);
				all.addArticle(art);
				Set<ArticleField> fields = new HashSet<ArticleField>();
				fields.add(all);
				
				art.setFields(fields);
				
				setResponsePage(ArticlesPage.class);
			}
		});
		
		FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);
		add(form);
	}

	@SuppressWarnings("serial")
	public ArticleAddPage(Article article) {		
		Form<Article> form = new Form<Article>("form", new CompoundPropertyModel<Article>(new EntityModel<Article>(Article.class, article)));
		form.add(new ArticleInfoPanel("articleInfo"));
		form.add(new Button("save", new ResourceModel("save")) {
			@Override
			public void onSubmit() {
				setResponsePage(ArticlesPage.class);
			}
		});
		
		FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);
		add(form);
	}
}
